/**
 * 用户状态管理模块
 * 独立模块，避免单一文件过大
 */

import { defineStore } from 'pinia'
import request from '@/utils/request'
import type { User, Department, Position } from '@/types/user'

interface UserState {
  users: User[]
  userTotal: number
  departments: Department[]
  positions: Position[]
  positionTotal: number
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    users: [],
    userTotal: 0,
    departments: [],
    positions: [],
    positionTotal: 0,
  }),

  getters: {
    // 启用状态的用户
    activeUsers: state => state.users.filter(user => user.status === 1),

    // 部门树（扁平化为树形结构）
    departmentTree: (state): Department[] => {
      // 简单实现，实际项目中可能需要更复杂的树形结构
      return state.departments
    },

    // 岗位选项
    positionOptions: state => {
      return state.positions
        .filter(position => position.status === 1)
        .map(position => ({
          label: position.title,
          value: position.id,
        }))
    },
  },

  actions: {
    // 获取用户列表
    async getUserList(params?: any) {
      try {
        const res: any = await request({
          url: '/api/user/user/index',
          method: 'get',
          params,
        })
        if (res.code === 0) {
          this.users = res.data.list
          this.userTotal = res.data.total || 0
        }
        return res
      } catch (error) {
        throw error
      }
    },

    // 添加用户
    async addUser(data: any) {
      const res: any = await request({
        url: '/api/user/user/add',
        method: 'post',
        data,
      })
      // 添加成功后刷新列表
      if (res.code === 0) {
        await this.getUserList()
      }
      return res
    },

    // 编辑用户
    async updateUser(id: number, data: any) {
      const res: any = await request({
        url: `/api/user/user/update/${id}`,
        method: 'put',
        data,
      })
      if (res.code === 0) {
        await this.getUserList()
      }
      return res
    },

    // 删除用户
    async deleteUser(id: number) {
      const res: any = await request({
        url: '/api/user/user/delete',
        method: 'post',
        data: { id },
      })
      if (res.code === 0) {
        await this.getUserList()
      }
      return res
    },

    // 获取部门列表
    async getDepartments() {
      const res: any = await request({
        url: '/api/user/department/index',
        method: 'get',
      })
      if (res.code === 0) {
        this.departments = res.data
      }
      return res
    },

    // 添加/编辑部门
    async saveDepartment(data: any) {
      const url = data.id ? `/api/user/department/update/${data.id}` : '/api/user/department/store'
      const method = data.id ? 'put' : 'post'

      const res: any = await request({
        url,
        method,
        data,
      })

      if (res.code === 0) {
        await this.getDepartments()
      }
      return res
    },

    // 删除部门
    async deleteDepartment(id: number) {
      const res: any = await request({
        url: '/api/user/department/del',
        method: 'delete',
        params: { id },
      })
      if (res.code === 0) {
        await this.getDepartments()
      }
      return res
    },

    // 获取岗位列表
    async getPositions(params?: any) {
      const res: any = await request({
        url: '/api/user/position/index',
        method: 'get',
        params,
      })
      if (res.code === 0) {
        this.positions = res.data
        this.positionTotal = (res as any).count || 0
      }
      return res
    },

    // 添加/编辑岗位
    async savePosition(data: any) {
      const res: any = await request({
        url: '/api/user/position/add',
        method: 'post',
        data,
      })
      if (res.code === 0) {
        await this.getPositions()
      }
      return res
    },

    // 删除岗位
    async deletePosition(id: number) {
      const res: any = await request({
        url: '/api/user/position/delete',
        method: 'post',
        data: { id },
      })
      if (res.code === 0) {
        await this.getPositions()
      }
      return res
    },

    // 重置状态
    resetState() {
      this.users = []
      this.userTotal = 0
      this.departments = []
      this.positions = []
      this.positionTotal = 0
    },
  },
})
